package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.common.market.ChargeMarketParams;
import com.zhentao.mapper.ChargeCouponMapper;
import com.zhentao.mapper.ChargeUserCouponMapper;
import com.zhentao.market.ChargeMarketThreadUtils;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.pojo.market.ChargeCoupon;
import com.zhentao.model.pojo.market.ChargeCouponCondition;
import com.zhentao.model.pojo.market.ChargeUserCoupon;
import com.zhentao.model.pojo.market.dto.ChargeUserCouponDto;
import com.zhentao.model.pojo.market.vo.ChargeCouponVo;
import com.zhentao.model.pojo.user.ChargeUser;
import com.zhentao.service.ChargeCouponConditionService;
import com.zhentao.service.ChargeCouponService;
import com.zhentao.service.ChargeUserCouponService;
import com.zhentao.service.CouponAsyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.zhentao.model.common.enums.AppHttpCodeEnum.PARAM_INVALID;
import static com.zhentao.model.common.enums.AppHttpCodeEnum.SERVER_ERROR;

/**
 * @author Wl177
 * @description 针对表【charge_user_coupon】的数据库操作Service实现
 * @createDate 2024-12-18 09:43:51
 */
@Service
@Slf4j
public class ChargeUserCouponServiceImpl extends ServiceImpl<ChargeUserCouponMapper, ChargeUserCoupon>
        implements ChargeUserCouponService {
    @Autowired
    private ChargeCouponService couponService;
    @Autowired
    private ChargeCouponConditionService conditionService;
    @Resource
    private CouponAsyncService couponAsyncService;


    /**
     * @param
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @description 获取每个登录用户的优惠卷个数  只查看可以使用的优惠卷个数
     * @author 振涛教育_小Q
     * @date 2024/12/22 21:35
     * @description 获取每个登录用户的优惠卷个数
     * @author 振涛教育_小Q
     * @date 2024/12/22 21:35
     */
    public ResponseResult UserCouponCount() {
        // 获取当前登录用户
        ChargeUser user = ChargeMarketThreadUtils.getChargeUserThreadLocal();
        if (user == null) {
            return ResponseResult.errorResult(SERVER_ERROR);
        }
        // 查询对应的优惠卷个数
        long count = list(Wrappers.<ChargeUserCoupon>lambdaQuery()
                .eq(StringUtils.checkValNotNull(user.getId()), ChargeUserCoupon::getUserId,
                        user.getId())
                .eq(ChargeUserCoupon::getStatus, 0)).size();
        return ResponseResult.okResult(count);
    }


    /**
     * @param dto
     * @return ResponseResult
     * @description: 优惠券列表
     */
    @Override
    public ResponseResult userCouponList(ChargeUserCouponDto dto) {
        // 判断参数是否有效
        if (dto == null) {
            return ResponseResult.errorResult(SERVER_ERROR);
        }
        // 获取用户id
        ChargeUser user = ChargeMarketThreadUtils.getChargeUserThreadLocal();
        if (StringUtils.checkValNull(user)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.CHARGE_USER_DATA_NOT_EXIST);
        }
        // 分页
        Page<ChargeUserCoupon> page = new Page<>(dto.getPageNum(), dto.getPageSize());

        List<ChargeUserCoupon> chargeUserCoupons = new ArrayList<>();

        this.page(page, Wrappers.<ChargeUserCoupon>lambdaQuery()
                .eq(StringUtils.checkValNotNull(dto.getStatus()), ChargeUserCoupon::getStatus, dto.getStatus())
                .eq(StringUtils.checkValNotNull(user.getId()), ChargeUserCoupon::getUserId, user.getId())
                .orderByDesc(ChargeUserCoupon::getCreateTime));
        List<ChargeUserCoupon> records = page.getRecords();

        try {
            for (int i = 0; i < records.size(); i++) {
                ChargeUserCoupon coupon = records.get(i);
                ChargeCouponVo vo = new ChargeCouponVo();
                BeanUtils.copyProperties(coupon, vo);
                // 获取用户优惠卷的状态
                if (coupon.getStatus() != null) {
                    vo.setUserStatusName(ChargeMarketParams.CHARGE_MARKET_COUPON_USER_STATUS.get(coupon.getStatus()));
                }
                // 获取优惠卷
                if (coupon.getCouponId() != null) {
                    ChargeCoupon couponInfo = couponService.getById(coupon.getCouponId());
                    if (couponInfo != null) {
                        vo.setUserTypeName(ChargeMarketParams.CHARGE_MARKET_COUPON_USER_TYPE.get(couponInfo.getUseType()));
                        vo.setOverlayName(ChargeMarketParams.CHARGE_MARKET_COUPON_OVERLAY.get(couponInfo.getOverlay()));
                        vo.setPeriodUnitName(ChargeMarketParams.CHARGE_MARKET_COUPON_PERIOD_UNIT);
                        vo.setCoupon(couponInfo);
                        // 异步调用  判断优惠卷是否已经过期
                        Integer status = couponAsyncService.checkUserCouponExpire(couponInfo, coupon);
                        coupon.setStatus(status);
                        updateById(coupon);
                        // 获取优惠卷条件
                        if (couponInfo.getConditionId() != null) {
                            ChargeCouponCondition condition = conditionService.getById(couponInfo.getConditionId());
                            if (condition != null) {
                                vo.setTypeName(ChargeMarketParams.CHARGE_MARKET_COUPON_CONDITION_TYPE.get(condition.getType()));
                                vo.setCouponCondition(condition);
                            }
                        }
                    }
                }
                if (dto.getChargeStationInfoId() != null) {
                    if (vo.getCoupon().getChargeStationInfoId() == 0 || vo.getCoupon().getChargeStationInfoId().equals(dto.getChargeStationInfoId())) {
                        if (vo.getCouponCondition().getCondition() <= dto.getAmount()) {
                            chargeUserCoupons.add(vo);
                        }
                    }
                }else{
                    chargeUserCoupons.add(vo);
                }
            }
        } catch (NullPointerException e) {
            log.info("NullPointerException 异常：", e);
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        page.setRecords(chargeUserCoupons);


        return ResponseResult.okResult(page);
    }


    @Override
    public ResponseResult getCouponAmount(ChargeUserCouponDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(SERVER_ERROR);
        }
        System.out.println(dto + "======");
        List<Integer> selectedCouponIds = dto.getSelectedCouponIds();
        Double amount = dto.getAmount();
        for (Integer selectedCouponId : selectedCouponIds) {
            ChargeUserCoupon byId = this.getById(selectedCouponId);
            ChargeCoupon byId1 = couponService.getById(byId.getCouponId());
            ChargeCouponCondition byId2 = conditionService.getById(byId1.getConditionId());

            if (byId2.getFaceValue().doubleValue() >= 1) {
                amount = amount - byId2.getFaceValue().doubleValue();
            }
            if (byId2.getFaceValue().doubleValue() < 1) {
                amount = amount * byId2.getFaceValue().doubleValue();
            }

        }

        BigDecimal amountBD = new BigDecimal(amount).setScale(2, RoundingMode.HALF_UP);
        return ResponseResult.okResult(amountBD);
    }

}




